using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using UniversalAdmin.Application.Commands;
using UniversalAdmin.Application.Services;
using UniversalAdmin.Infrastructure.Data.Contexts;
using Microsoft.EntityFrameworkCore;

[ApiController]
[Route("api/dashboard")]
[Authorize]
public class DashboardController : ControllerBase
{
    private readonly AdminDbContext _db;
    private readonly ILogger<DashboardController> _logger;

    public DashboardController(AdminDbContext db, ILogger<DashboardController> logger)
    {
        _db = db;
        _logger = logger;
    }

    [HttpGet("stats")]
    public async Task<ApiResult> GetStats()
    {
        try
        {
            var stats = new
            {
                totalUsers = await _db.AppUsers.CountAsync(),
                totalRoles = await _db.AppRoles.CountAsync(),
                totalPermissions = await _db.AppPermissions.CountAsync(),
                totalConfigs = await _db.AppSystemConfigs.CountAsync()
            };

            return new ApiResult
            {
                Code = 200,
                Message = "获取统计数据成功",
                Data = stats,
                Timestamp = DateTime.UtcNow
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取统计数据失败");
            return new ApiResult
            {
                Code = 500,
                Message = "获取统计数据失败",
                Data = null,
                Timestamp = DateTime.UtcNow
            };
        }
    }

    [HttpGet("test")]
    public async Task<ApiResult> TestConnection()
    {
        try
        {
            var testData = new
            {
                canConnect = await _db.Database.CanConnectAsync(),
                usersCount = await _db.AppUsers.CountAsync(),
                rolesCount = await _db.AppRoles.CountAsync(),
                permissionsCount = await _db.AppPermissions.CountAsync(),
                configsCount = await _db.AppSystemConfigs.CountAsync(),
                tables = _db.Model.GetEntityTypes().Select(e => e.GetTableName()).ToList()
            };

            return new ApiResult
            {
                Code = 200,
                Message = "数据库连接测试成功",
                Data = testData,
                Timestamp = DateTime.UtcNow
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "数据库连接测试失败");
            return new ApiResult
            {
                Code = 500,
                Message = $"数据库连接测试失败: {ex.Message}",
                Data = null,
                Timestamp = DateTime.UtcNow
            };
        }
    }
} 